//
//  BackgroundProtocol.m
//  TabulaImaginarium8
//
//  Created by TA2 on 6/8/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BackgroundProtocol.h"


@implementation BackgroundProtocol

@synthesize selectionView;

- (void)dealloc {
    [selectionView release];
    selectionView = nil;
    [super dealloc];
}

- (void)readPacket:(NSArray *)packet fromSocket:(AsyncSocket *)socket {
	//NSString *dataString = [[NSString alloc] initWithData:packet encoding:NSUTF8StringEncoding];
	NSArray *arguments = packet;
	if ([arguments count] > 1) {
		if ([[arguments objectAtIndex:1] isEqualToString:@"SMT"]) {
			if ([Players sharedLocalPlayer].isHost) {
				[[NetworkController sharedNetworkController] sendDataToAll:[NetworkController argumentArrayToData:arguments] withTag:0 butSocket:socket];
			}
            NSString *path = [arguments objectAtIndex:2];
            if ([path isEqualToString:@"nil"]) {
                path = nil;
            }
			CGPoint point = (CGPoint){[[arguments objectAtIndex:3] intValue], [[arguments objectAtIndex:4] intValue]};
			[contentView.backgroundView.map setTileImage:[path lastPathComponent] atPoint:point];
			[contentView.backgroundView setNeedsDisplayInRect:CGRectMake(point.x * contentView.backgroundView.tileSize.width, point.y * contentView.backgroundView.tileSize.height, 
																			 contentView.backgroundView.tileSize.width, contentView.backgroundView.tileSize.height)];
		} else if ([[arguments objectAtIndex:1] isEqualToString:@"RMT"]) {
			CGPoint point = (CGPoint){[[arguments objectAtIndex:2] intValue], [[arguments objectAtIndex:3] intValue]};
			NSString *path = [contentView.backgroundView.map backgroundPathForPoint:point];
			if (path) {
				[self sendBackground:path atPoint:point toSocket:socket];
			}
		} else if ([[arguments objectAtIndex:1] isEqualToString:@"RMTA"]) {
            [self sendSuspend];
            NSArray *modifiedTiles = [contentView.backgroundView.map getAllModifiedTilePoints];
            for (NSValue *pointValue in modifiedTiles) {
                CGPoint point = [pointValue CGPointValue];
                NSString *path = [contentView.backgroundView.map backgroundPathForPoint:point];
                if (path) {
                    [self sendBackground:path atPoint:point toSocket:socket];
                }
            }
            contentView.suspensionCount--;
            if (contentView.suspensionCount == 0) {
                [contentView enableUI];
            }
            [self sendContinue];
		} else if ([[arguments objectAtIndex:1] isEqualToString:@"SMB"]) {
			if ([Players sharedLocalPlayer].isHost) {
				[[NetworkController sharedNetworkController] sendDataToAll:[NetworkController argumentArrayToData:arguments] withTag:0 butSocket:socket];
			}
            NSString *path = [arguments objectAtIndex:2];
            if ([path isEqualToString:@"nil"]) {
                path = nil;
            }
            @synchronized (contentView.backgroundView.map.backgroundImage) {
                contentView.backgroundView.map.backgroundImage = path;
                [contentView.backgroundView.map clearLoadedBackgroundImage];
            }
            [selectionView selectMainBackgroundIcon:path];
			[contentView.backgroundView setNeedsDisplay];
		} else if ([[arguments objectAtIndex:1] isEqualToString:@"RMB"]) {
			[self sendMainBackground:contentView.backgroundView.map.backgroundImage toSocket:socket];
		} else if ([[arguments objectAtIndex:1] isEqualToString:@"RS"]) {
            contentView.suspensionCount++;
            if (contentView.suspensionCount > 0) {
                [contentView disableUI];
            }
        } else if ([[arguments objectAtIndex:1] isEqualToString:@"RC"]) {
            contentView.suspensionCount--;
            if (contentView.suspensionCount == 0) {
                [contentView enableUI];
            }
        }
	}
}

- (void)sendBackground:(NSString *)path atPoint:(CGPoint)point {
	//SMT: Send modified tile
    if (!path) {
        path = @"nil";
    }
	NSString *dataString = [[stringTag stringByAppendingString:[[[@"|SMT|" stringByAppendingString:path] stringByAppendingString:@"|"] 
															   stringByAppendingString:[NSString stringWithFormat:@"%f|%f", point.x, point.y]]] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)sendBackground:(NSString *)path atPoint:(CGPoint)point toSocket:(AsyncSocket *)socket {
	//SMT: Send modified tile
	NSString *dataString = [[stringTag stringByAppendingString:[[[@"|SMT|" stringByAppendingString:path] stringByAppendingString:@"|"] 
							stringByAppendingString:[NSString stringWithFormat:@"%f|%f", point.x, point.y]]] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendData:data toSocket:socket withTag:0];
}

- (void)sendRequestForBackground:(CGPoint)point {
	//RMT: Request modified tile
	NSString *dataString = [[stringTag stringByAppendingString:[@"|RMT|" stringByAppendingString:[NSString stringWithFormat:@"%f|%f", point.x, point.y]]] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)sendRequestForAllBackground {
	//RMTA: Request modified tile all
	NSString *dataString = [[stringTag stringByAppendingString:@"|RMTA"] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)sendMainBackground:(NSString *)path {
	//SMT: Send main background
    if (!path) {
        path = @"nil";
    }
	NSString *dataString = [[stringTag stringByAppendingString:[@"|SMB|" stringByAppendingString:path]] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)sendMainBackground:(NSString *)path toSocket:(AsyncSocket *)socket {
	//SMB: Send main background
    if (!path) {
        path = @"nil";
    }
	NSString *dataString = [[stringTag stringByAppendingString:[@"|SMB|" stringByAppendingString:path]] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendData:data toSocket:socket withTag:0];
}

- (void)sendRequestForMainBackground {
	//RMT: Request main background
	NSString *dataString = [[stringTag stringByAppendingString:@"|RMB"] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)sendSuspend {
    //RS: Request suspended mode
	NSString *dataString = [[stringTag stringByAppendingString:@"|RS"] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)sendContinue {
    //RC: Request continue from suspended mode
	NSString *dataString = [[stringTag stringByAppendingString:@"|RC"] stringByAppendingString:@"|≤|"];
	NSData *data = [dataString dataUsingEncoding: NSUTF8StringEncoding];
	[[NetworkController sharedNetworkController] sendDataToAll:data withTag:0];
}

- (void)setupProtocol {
	if (![Players sharedLocalPlayer].isHost) {
		[self sendRequestForMainBackground];
		[self sendRequestForAllBackground];
	}
}

@end
